package leju.common.update;

import java.io.File;

import leju.common.filedownload.AsyncDownLoadManager;
import leju.common.filedownload.AsyncDownLoadManager.OnDownLoadListener;
import leju.common.filedownload.WebResource;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.leju.common.R;
import com.leju.common.util.FileUtils;
import com.leju.common.util.Logger;

/**
 * 下载Apk文件 ，下载完成后自动安装。
 * 
 * @author liuwei
 * 
 */
public class ApkDownloader {
	private Activity activity = null;
	private String apkName;
	private String apkUrl;
	private int iconResouId;
	private int apkId = 123456;
	// 通知栏
	private NotificationManager notificationManager = null;
	private Notification notification = null;

	public ApkDownloader(Activity activity, String url) {
		this.activity = activity;
		this.apkUrl = url;
	}

	public ApkDownloader(Activity activity, String url, int iconResouceId) {
		apkUrl = url;
		this.iconResouId = iconResouceId;
		this.activity = activity;
	}

	public void setApkId(int id) {
		apkId = id;
	}

	/**
	 * 
	 * 
	 * @param activity
	 * @param url
	 * @param iconResouceId
	 * @param apkName
	 */
	public ApkDownloader(Activity activity, String url, int iconResouceId,
			String apkName) {
		apkUrl = url;
		this.iconResouId = iconResouceId;
		this.apkName = apkName;
		this.activity = activity;
	}

	private void showDownLoadNotification() {
		notificationManager = (NotificationManager) activity
				.getSystemService(Context.NOTIFICATION_SERVICE);
		notification = new Notification();
		notification.contentView = new RemoteViews(activity.getPackageName(),
				R.layout.notice_view);
		if (iconResouId != 0) {
			notification.contentView.setImageViewResource(R.id.notice_view_image, iconResouId);
			notification.icon = iconResouId;
		}

		notification.tickerText = apkName + "开始下载更新";

		Intent intent = new Intent();

		PendingIntent pIntent = PendingIntent.getActivity(
				activity.getApplicationContext(), 0, intent, 0);
		notification.contentIntent = pIntent;
		notificationManager.notify(apkId, notification);

	}

	/**
	 * 下载安装包
	 * 
	 * @param url
	 *            下载地址
	 * @param appName
	 *            要下载的应用名字
	 */
	public void downLoadApp() {
		showDownLoadNotification();
		AsyncDownLoadManager downLoadManager = AsyncDownLoadManager
				.getAsyncManager(activity);
		WebResource mResource = new WebResource();
		String path = "Android/data/" + activity.getPackageName();
		File file = new FileUtils(activity.getApplicationContext())
				.creatSDDir(path);
		mResource.filePath = file.getAbsolutePath() + "/";
		Logger.e(mResource.filePath);
		mResource.url = apkUrl;
		mResource.fileName = apkUrl.substring(apkUrl.lastIndexOf("/") + 1);
		downLoadManager.addDownTask(mResource, onDownLoadListener);

	}

	int currentProgress = 0;
	OnDownLoadListener onDownLoadListener = new OnDownLoadListener() {

		@Override
		public void onUpdataDownLoadProgross(WebResource Resource, int progross) {
			if (progross > currentProgress) {

				notification.contentView.setTextViewText(R.id.notice_view_text,
						apkName + "已下载" + progross + "%");
				notification.contentView.setProgressBar(
						R.id.notice_view_progress, 100, progross, false);
				notificationManager.notify(apkId, notification);
			}

			currentProgress = progross;

		}

		@Override
		public void onFinshDownLoad(WebResource mResource) {

			// dialog.dismiss();
			File appFile = new File(mResource.filePath + mResource.fileName);
			// 点击安装PendingIntent
			// Uri uri = Uri.fromFile(appFile);
			// Intent installIntent = new Intent(Intent.ACTION_VIEW);
			// installIntent.setDataAndType(uri,
			// "application/vnd.android.package-archive");
			// updatePendingIntent = PendingIntent.getActivity(activity, 0,
			// installIntent, 0);
			//
			// notification.defaults = Notification.DEFAULT_SOUND;// 铃声提醒
			// notification.tickerText = apkName + "下载完成,请点击安装。";
			// notification.contentIntent = updatePendingIntent;
			// // notification.setLatestEventInfo(activity, appName,
			// "下载完成,点击安装。",
			// // updatePendingIntent);
			// notificationManager.notify(apkId, notification);
			openFile(appFile);
			notificationManager.cancel(apkId);
			// Logger.e(appFile.getAbsolutePath());
			// Intent intent = new Intent(Intent.ACTION_VIEW);
			//
			// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			//
			// intent.setDataAndType(Uri.parse(appFile.getAbsolutePath()),
			// "application/vnd.android.package-archive");
			//
			// activity.startActivity(intent);

		}

		private void openFile(File f) {
			Intent intent = new Intent();
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setAction(android.content.Intent.ACTION_VIEW);
			String type = getMIMEType(f);
			intent.setDataAndType(Uri.fromFile(f), type);
			activity.startActivity(intent);
		}

		private String getMIMEType(File f) {
			String type = "";
			String fName = f.getName();
			String end = fName.substring(fName.lastIndexOf(".") + 1,
					fName.length()).toLowerCase();
			if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
					|| end.equals("xmf") || end.equals("ogg")
					|| end.equals("wav")) {
				type = "audio";
			} else if (end.equals("3gp") || end.equals("mp4")) {
				type = "video";
			} else if (end.equals("jpg") || end.equals("gif")
					|| end.equals("png") || end.equals("jpeg")
					|| end.equals("bmp")) {
				type = "image";
			} else if (end.equals("apk")) {
				type = "application/vnd.android.package-archive";
			} else {
				type = "*";
			}
			if (end.equals("apk")) {
			} else {
				type += "/*";
			}
			return type;
		}

		@Override
		public void onError(String error) {
			Toast.makeText(activity.getApplicationContext(), error,
					Toast.LENGTH_SHORT).show();

		}
	};
}
